import os
import logging
from concurrent_log_handler import ConcurrentRotatingFileHandler
from datetime import datetime

def setup_logger(app_name='app', log_level=logging.INFO):
    """
    配置日志记录器
    :param app_name: 应用名称
    :param log_level: 日志级别
    :return: logger实例
    """
    # 创建logs目录
    log_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'logs')
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)

    # 设置日志文件路径
    log_file = os.path.join(log_dir, f'{app_name}.log')

    # 创建logger实例
    logger = logging.getLogger(app_name)
    logger.setLevel(log_level)

    # 使用 ConcurrentRotatingFileHandler 替代 TimedRotatingFileHandler
    file_handler = ConcurrentRotatingFileHandler(
        filename=log_file,
        maxBytes=10*1024*1024,  # 10MB
        backupCount=30,
        encoding='utf-8'
    )

    # 设置日志格式
    formatter = logging.Formatter(
        '[%(asctime)s] %(levelname)s in %(module)s: %(message)s'
    )
    file_handler.setFormatter(formatter)

    # 添加处理器
    if not logger.handlers:
        logger.addHandler(file_handler)

        # 添加控制台输出
        console_handler = logging.StreamHandler()
        console_handler.setFormatter(formatter)
        logger.addHandler(console_handler)

    return logger

# 创建默认logger实例
logger = setup_logger('exhibition')